<template>
	<el-card shadow="never" class="admin_index_article">
		<template slot="header">
			<h4>浏览及来访IP统计</h4>
			<el-radio-group v-model="scopeDate" size="mini">
				<el-radio-button label="day">今日</el-radio-button>
				<el-radio-button label="month">本月</el-radio-button>
				<el-radio-button label="year">全年</el-radio-button>
			</el-radio-group>
		</template>
		<div class="echarts" ref="chart"></div>
	</el-card>
</template>

<script>
import lodash from 'lodash';
import * as echarts from 'echarts';
import { getClickChart } from '@/api/statistics';
const debounce = (func, wait) => {
	let timeout;
	return function () {
		const context = this;
		const args = arguments;
		clearTimeout(timeout);
		timeout = setTimeout(() => func.apply(context, args), wait);
	};
};
export default {
	data() {
		return {
			scopeDate: 'month',
			chartInstance: null,
			chartOption: {
				legend: { show: true },
				tooltip: { trigger: 'axis' },
				xAxis: { type: 'category', data: [] },
				yAxis: { type: 'value', axisLine: { show: true, lineStyle: { color: '#909399' } } },
				grid: { top: 48, left: 0, right: 0, bottom: 0, containLabel: true },
				series: []
			}
		};
	},
	watch: {
		scopeDate: {
			async handler(val) {
				await this.getClickChartData(val);
				this.chartInstance.setOption(this.chartOption);
			},
			immediate: true
		}
	},
	mounted() {
		this.initializeChart();
		window.addEventListener(
			'resize',
			debounce(() => {
				this.chartInstance.resize();
			}, 200)
		);
	},
	methods: {
		initializeChart() {
			let chartDom = this.$refs['chart'];
			this.chartInstance = new echarts.init(chartDom);
		},

		async getClickChartData(scope) {
			let result = await getClickChart({ scope }).then((res) => res.data);
			if (result.code === '0') {
				let seriesData = [];
				let datas = this.$detailData(result.data);
				for (let key in datas) {
					let obj = { type: 'line', smooth: true };
					if (key === 'click') {
						obj['name'] = '浏览量';
					} else if (key === 'ip') {
						obj['name'] = '来访IP';
					}
					seriesData.push({ ...obj, data: datas[key].map((n) => Number(n.num)) });
				}
				this.chartOption.xAxis.data = lodash.map(datas.ip, 'formatTime');
				this.chartOption.series = seriesData;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.admin_index_article {
	flex: 4;
	/* height: calc(50% - 130px); */
}
</style>
